import {
  addSearch,
  querySearch,
  removeSearch,
  updateSearch,
  queryOceanShipping,
  getAreaStreetsTree,
  getAreaTree,
} from './service';

const Model = {
  namespace: 'searchList',
  state: {
    content: {
      list: [],
      pege: {},
    },
  },
  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(querySearch, { ...payload });
      yield put({
        type: 'save',
        payload: response,
      });
    },

    *queryOceanShipping({ payload }, { call, put }) {
      const response = yield call(queryOceanShipping, { ...payload });
      yield put({
        type: 'save',
        payload: response,
      });
    },

    *add({ payload, callback }, { call, put }) {
      const response = yield call(addSearch, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },

    *remove({ payload, callback }, { call, put }) {
      const response = yield call(removeSearch, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },

    *update({ payload, callback }, { call, put }) {
      const response = yield call(updateSearch, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },

    /** 获取区域 */
    *getAreaTree({}, { call, put, select }) {
      const areaTreeSession = sessionStorage.getItem('areaTree');
      if (!areaTreeSession) {
        const res = yield call(getAreaTree);
        if (res.data.resultCode === 'ok') {
          let data = res.data.content;
          sessionStorage.setItem('areaTree', JSON.stringify(data)); //sessionStorage只能存字符串
          yield put({
            type: 'setAreaTree',
            payload: {
              areaTree: data,
            },
          });
          //if (onSuccess) onSuccess(data);
        }
      } else {
        yield put({
          type: 'setAreaTree',
          payload: {
            areaTree: JSON.parse(areaTreeSession),
          },
        });
      }
    },

    /** 获取街道级联树 */
    *getAreaStreetsTree({ districtCode, onSuccess }, { call, put, select }) {
      const res = yield call(getAreaStreetsTree, { districtCode });
      if (res.data.resultCode === 'ok') {
        let data = res.data.content;
        let streets = [];
        (data ? data : []).map(row => {
          streets.push({ label: row.streetsName, value: row.streetsCode });
        });
        if (onSuccess) {
          onSuccess(streets);
        }
      }
    },
  },

  reducers: {
    save(state, action) {
      return { ...state, content: action.payload.content };
    },

    /** 设置省市级联树 */
    setAreaTree(state, { payload }) {
      return { ...state, areaTree: payload.areaTree };
    },
  },
};
export default Model;
